<?php
namespace app\admin\controller;
use think\Request;
use think\Db;
use think\Config;

class Supplier extends Base
{
	/**
	 * 供应商列表
	 * @return [type] [description]
	 */
	function index(){
		$keywords = Request::instance()->param("keywords",'');
        $query= Db::field("s.*,u.username as admin")
        		->table( 'sdzx_supplier' )->alias('s')
                ->join('sdzx_supplier_user u','s.supplier_id=u.supplier_id and u.is_super=1','left');
        if ( !empty($keywords) ) {
            $query->where('supplier_name|charge|charge_phone', 'like', '%'.$keywords.'%');
        }
        $data['list'] = $query->paginate('',false,['query'=>Request()->param()]);
		return $this->fetch('index',$data);
	}

	/**
	 * 添加
	 */
	function add(){
		if (Request()->isPost()) {
			$params = Request()->only('supplier_name,charge,charge_phone,supplier_status,username,password,remark','post');
			empty($params['supplier_name']) && $this->error('供应商名必须填写');
			empty($params['charge']) && $this->error('供应商负责人必须填写');
			empty($params['charge_phone']) && $this->error('供应商负责人电话必须填写');
			empty($params['username']) && $this->error('供应商管理员必须填写');
			empty($params['password']) && $this->error('供应商管理员密码必须填写');

			$username = trim($params['username']); unset($params['username']);
			$password = $params['password']; unset($params['password']);

			//查看供应商名是否存在
			$issetSupplier = Db::name('supplier')->where(['supplier_name'=>$params['supplier_name']])->find();
			$issetSupplier && $this->error('供应商已存在');
			//查看管理员账号是否存在
			$issetUsername = Db::name('supplier_user')->where(['username'=>$username])->find();
			$issetUsername && $this->error('管理员账号已存在');

			Db::startTrans();
			$supplier_id = Db::name('supplier')->insertGetId($params);
			if (!$supplier_id) {Db::rollback();$this->error('操作失败');}

			$user = [
				'supplier_id' => $supplier_id,
				'username'    => $username,
				'password'    => md5($password),
				'is_super'    => 1
			];
			$user_id = Db::name('supplier_user')->insertGetId($user);
			if (!$user_id) {Db::rollback();$this->error('操作失败');}

			$re_sup = Db::name('supplier')->where(['supplier_id'=>$supplier_id])->update(['admin_id'=>$this->uid]);
			if ($re_sup) {
				Db::commit();
				$this->success('操作成功','','refresh');
			}else{
				Db::rollback();
				$this->error('操作失败');
			}
		}else{
			return $this->fetch();
		}
	}

	/**
	 * 编辑
	 * @return [type] [description]
	 */
	function edit(){
		
		if (Request()->isPost()) {
			$params = Request()->only('supplier_id,supplier_name,charge,charge_phone,supplier_status,username,password,remark','post');

			!isset($params['supplier_id']) && $this->error('参数错误');
			empty($params['supplier_name']) && $this->error('供应商名必须填写');
			empty($params['charge']) && $this->error('供应商负责人必须填写');
			empty($params['charge_phone']) && $this->error('供应商负责人电话必须填写');
			empty($params['username']) && $this->error('供应商管理员必须填写');
			
			$username = trim($params['username']); unset($params['username']);
			$password = $params['password']; unset($params['password']);

			//查看供应商名是否存在
			$issetSupplier = Db::name('supplier')->where(['supplier_name'=>$params['supplier_name'],'supplier_id'=>['neq',$params['supplier_id']]])->find();
			$issetSupplier && $this->error('供应商已存在');

			//找出管理员ID
			$admin_id = Db::name('supplier_user')->where(['supplier_id'=>$params['supplier_id'],'is_super'=>1])->value('id');

			$w = ['username'=>$username];
			if ($admin_id) {
				$w['id']=['neq',$admin_id];
			}else{
				empty($password) && $this->error('供应商管理员密码必须填写');
			}
			//查看管理员账号是否存在
			$issetUsername = Db::name('supplier_user')->where($w)->find();
			$issetUsername && $this->error('管理员账号已存在');

			Db::startTrans();
			$re = Db::name('supplier')->where(['supplier_id'=>$params['supplier_id']])->update($params);
			if ($re===false) {Db::rollback();$this->error('操作失败');}

			$user = [
				'username'    => $username,
				'supplier_id' => $params['supplier_id'],
			];

			if ($password) {
				$user['password'] = md5($password);
			}
			
			if ($admin_id) {
				$re_user = Db::name('supplier_user')->where(['id'=>$admin_id])->update($user);
			}else{
				$user['is_super'] = 1;
				$re_user = Db::name('supplier_user')->insertGetId($user);
				if (!$re_user) {Db::rollback();$this->error('操作失败');}

//				$re_sup = Db::name('supplier')->where(['supplier_id'=>$params['supplier_id']])->update(['admin_id'=>$re_user]);
//				if ($re_sup === false) {Db::rollback();$this->error('操作失败');}
			}
			
			if ($re_user!==false) {
				Db::commit();
				$this->success('操作成功','','refresh');
			}else{
				Db::rollback();
				$this->error('操作失败');
			}
		}else{
			$params = Request()->param();
			!isset($params['supplier_id']) && $this->error('参数错误');

			$info = Db::field("s.*,u.username")
        		->table( 'sdzx_supplier' )->alias('s')
                ->join('sdzx_supplier_user u','s.supplier_id=u.supplier_id and u.is_super=1','left')
                ->where("s.supplier_id={$params['supplier_id']}")
                ->find();
            $data = ['info'=>$info];
			return $this->fetch('edit',$data);
		}
	}

	/**
	 * 快捷编辑
	 * @return [type] [description]
	 */
	function quickEdit(){
		$params = Request()->param();
		if (!isset($params['supplier_id']) || !isset($params['colum']) || !isset($params['value']) || $params['value'] == null) {
			$this->error('参数错误');
		}
		$data[$params['colum']] = $params['value'];
		$re = Db::name('supplier')->where(['supplier_id'=>$params['supplier_id']])->update($data);
		if ($re !== false) {
			$this->success('操作成功','',$data);
		}else{
			$this->error('操作失败');
		}
	}

	/**
	 * 删除
	 * @return [type] [description]
	 */
	function del(){
		$ids = Request()->param('ids');
		if (empty($ids)) {
			$this->error('参数错误');
		}
		Db::startTrans();
		//查看供应商是否绑定在商品中
		$bind = Db::name('goods_specval')->where(['supplier_id'=>['in',$ids]])->find();
        $goods_name = Db::name('goods')->where(['goods_id'=>$bind['goods_id']])->value('goods_name');
		$bind && $this->error("供应商绑定在商品【{$goods_name}】上不能删除");

		$del_1 = Db::name('supplier')->where(['supplier_id'=>['in',$ids]])->delete();
		$del_2 = Db::name('supplier_user')->where(['supplier_id'=>['in',$ids]])->delete();

		//删除申请记录
		if (Db::name('supplier_apply')->where(['supplier_id'=>['in',$ids]])->find()){
            $del_3 = Db::name('supplier_apply')->where(['supplier_id'=>['in',$ids]])->delete();
        }else{
		    $del_3 = true;
        }


		if ($del_1 && $del_2 && $del_3) {
		    Db::commit();
			$this->success('删除成功','');
		}else{
		    Db::rollback();
			$this->error('删除失败');
		}
	}
}